<template>
    <view class="login-container">
        <!-- 后退按钮 - 放在最顶部 -->
        <view
            class="header"
            v-if="
                loginType === 'password' || (loginType === 'sms' && step === 2)
            "
        >
            <view
                class="back-icon"
                @click="loginType === 'password' ? goToSmsLogin() : goBack()"
            >
                <roc-icon-plus
                    type="fas"
                    name="angle-left"
                    :size="20"
                    color="#333"
                ></roc-icon-plus>
            </view>
        </view>

        <view class="logo-box">
            <image
                v-if="!(loginType === 'sms' && step === 2)"
                class="logo"
                src="/static/images/logo2.png"
                mode="aspectFit"
            ></image>
        </view>

        <!-- 手机验证码登录-输入手机号页面 -->
        <block v-if="loginType === 'sms' && step === 1">
            <view class="page-title"> 账号登录 </view>
            <view class="page-subtitle"> 请输入账号验证码登录 </view>

            <view class="form-box">
                <view class="input-item">
                    <input
                        type="text"
                        v-model="phone"
                        placeholder="请输入手机号"
                        placeholder-class="placeholder"
                    />
                </view>

                <button class="login-btn" @click="getVerifyCode">
                    获取验证码
                </button>

                <view class="bottom-options">
                    <view class="switch-login" @click="switchToPasswordLogin">
                        密码登录
                    </view>

                    <view class="agreement">
                        <checkbox-group>
                            <label>
                                <checkbox
                                    :checked="isAgree"
                                    @tap="toggleAgreement"
                                    color="#2EB57D"
                                />
                                <text>已阅读并同意 </text>
                                <text class="link">《用户协议》</text>
                            </label>
                        </checkbox-group>
                    </view>
                </view>
            </view>
        </block>

        <!-- 手机验证码登录-输入验证码页面 -->
        <block v-if="loginType === 'sms' && step === 2">
            <view class="page-title"> 输入验证码 </view>
            <view class="page-subtitle">
                已发送至 +86 {{ formatPhone(phone) }}
            </view>

            <view class="form-box">
                <view class="verify-code-input">
                    <view
                        class="code-item"
                        v-for="(item, index) in 4"
                        :key="index"
                    >
                        <input
                            type="text"
                            :value="smsCode[index] || ''"
                            maxlength="1"
                            :focus="codeIndex === index"
                            @input="inputCode($event, index)"
                            @focus="codeIndex = index"
                        />
                    </view>
                </view>

                <view class="resend-btn" @click="resendCode">
                    重新发送
                    <text v-if="countdown > 0">({{ countdown }}秒)</text>
                </view>
            </view>
        </block>

        <!-- 账号密码登录页面 -->
        <block v-if="loginType === 'password'">
            <view class="page-title"> 账号登录 </view>
            <view class="page-subtitle"> 请输入账号密码登录 </view>

            <view class="form-box">
                <view class="input-item">
                    <input
                        type="text"
                        v-model="account"
                        placeholder="请输入账号"
                        placeholder-class="placeholder"
                    />
                </view>

                <view class="input-item">
                    <input
                        :type="showPassword ? 'text' : 'password'"
                        v-model="password"
                        placeholder="请输入密码"
                        placeholder-class="placeholder"
                    />
                    <view class="eye-icon" @click="togglePasswordVisibility">
                        <roc-icon-plus
                            type="fas"
                            :name="showPassword ? 'eye' : 'eye-slash'"
                            :size="20"
                            color="#999"
                        ></roc-icon-plus>
                    </view>
                </view>

                <!-- <view class="forgot-password" @click="toForgotPassword"
                    >忘记密码</view
                > -->

                <button class="login-btn" @click="handleLogin">登录</button>

                <view class="agreement">
                    <checkbox-group>
                        <label>
                            <checkbox
                                :checked="isAgree"
                                @tap="toggleAgreement"
                                color="#2EB57D"
                            />
                            <text>已阅读并同意 </text>
                            <text class="link">《用户协议》</text>
                        </label>
                    </checkbox-group>
                </view>
            </view>
        </block>
    </view>
</template>

<script>
import { user } from "@/utils/api/index.js";

export default {
    data() {
        return {
            loginType: "sms", // 'sms'或'password'
            step: 1, // 验证码登录步骤：1-输入手机号，2-输入验证码
            phone: "",
            smsCode: [],
            codeIndex: 0,
            account: "",
            password: "",
            showPassword: false,
            isAgree: true,
            countdown: 0,
            timer: null,
        };
    },
    methods: {
        formatPhone(phone) {
            if (!phone) return "";
            return phone.replace(/(\d{3})(\d{4})(\d{4})/, "$1 $2 $3");
        },
        goBack() {
            if (this.loginType === "sms" && this.step === 2) {
                this.step = 1;
            }
        },
        goToSmsLogin() {
            this.loginType = "sms";
            this.step = 1;
        },
        switchToPasswordLogin() {
            this.loginType = "password";
        },
        togglePasswordVisibility() {
            this.showPassword = !this.showPassword;
        },
        toggleAgreement() {
            this.isAgree = !this.isAgree;
        },
        getVerifyCode() {
            if (!this.isAgree) {
                uni.showToast({
                    title: "请先同意用户协议",
                    icon: "none",
                });
                return;
            }

            if (!this.phone || !/^1\d{10}$/.test(this.phone)) {
                uni.showToast({
                    title: "请输入正确的手机号",
                    icon: "none",
                });
                return;
            }

            // 调用获取验证码接口
            const data = {
                mobile: this.phone,
                captchaVerification: "", // 如果需要图形验证码，这里需要传入
                scene: 1 // 场景值，1表示登录
            };

            user.sendSmsCode(data)
                .then((res) => {
                    // 处理不同的返回码
                    if (res.code === 0) {
                        // 成功发送验证码
                        this.countdown = 60;
                        this.startCountdown();
                        this.step = 2;
                        this.smsCode = [];
                        this.codeIndex = 0;

                        uni.showToast({
                            title: "验证码已发送",
                            icon: "success",
                        });
                    } else {
                        // 处理其他错误码
                        let errorMsg = res.msg || "获取验证码失败";
                        
                        // 特殊处理手机号不存在的错误码
                        if (res.code === 1002000007) {
                            errorMsg = "手机号不存在，请检查后重试";
                        }
                        
                        uni.showToast({
                            title: errorMsg,
                            icon: "none",
                        });
                    }
                })
                .catch((err) => {
                    console.error("获取验证码失败:", err);
                    let errorMsg = "获取验证码失败";
                    
                    // 处理网络错误或其他异常
                    if (err.data && err.data.code === 1002000007) {
                        errorMsg = "手机号不存在，请检查后重试";
                    } else if (err.data && err.data.msg) {
                        errorMsg = err.data.msg;
                    }
                    
                    uni.showToast({
                        title: errorMsg,
                        icon: "none",
                    });
                });
        },
        resendCode() {
            if (this.countdown > 0) return;

            // 调用获取验证码接口
            const data = {
                mobile: this.phone,
                captchaVerification: "", // 如果需要图形验证码，这里需要传入
                scene: 1 // 场景值，1表示登录
            };

            user.sendSmsCode(data)
                .then((res) => {
                    // 处理不同的返回码
                    if (res.code === 0) {
                        // 成功发送验证码
                        this.countdown = 60;
                        this.startCountdown();
                        this.smsCode = [];
                        this.codeIndex = 0;

                        uni.showToast({
                            title: "验证码已重新发送",
                            icon: "success",
                        });
                    } else {
                        // 处理其他错误码
                        let errorMsg = res.msg || "获取验证码失败";
                        
                        // 特殊处理手机号不存在的错误码
                        if (res.code === 1002000007) {
                            errorMsg = "手机号不存在，请检查后重试";
                        }
                        
                        uni.showToast({
                            title: errorMsg,
                            icon: "none",
                        });
                    }
                })
                .catch((err) => {
                    console.error("获取验证码失败:", err);
                    let errorMsg = "获取验证码失败";
                    
                    // 处理网络错误或其他异常
                    if (err.data && err.data.code === 1002000007) {
                        errorMsg = "手机号不存在，请检查后重试";
                    } else if (err.data && err.data.msg) {
                        errorMsg = err.data.msg;
                    }
                    
                    uni.showToast({
                        title: errorMsg,
                        icon: "none",
                    });
                });
        },
        startCountdown() {
            if (this.timer) {
                clearInterval(this.timer);
            }

            this.timer = setInterval(() => {
                this.countdown--;
                if (this.countdown <= 0) {
                    clearInterval(this.timer);
                }
            }, 1000);
        },
        inputCode(event, index) {
            const value = event.detail.value;

            // 更新当前输入框的值
            this.$set(this.smsCode, index, value);

            // 自动跳转到下一个输入框
            if (value && index < 3) {
                this.codeIndex = index + 1;
            }

            // 如果已输入完所有验证码
            if (this.smsCode.filter(Boolean).length === 4) {
                this.handleVerifyCodeLogin();
            }
        },
        handleVerifyCodeLogin() {
            const code = this.smsCode.join("");

            if (code.length !== 4) {
                uni.showToast({
                    title: "请输入完整验证码",
                    icon: "none",
                });
                return;
            }

            // 调用短信验证码登录接口
            uni.showLoading({
                title: "登录中...",
            });

            const data = {
                mobile: this.phone,
                code: code,
            };

            user.smsLogin(data)
                .then((res) => {
                    uni.hideLoading();
                    
                    // 处理不同响应情况
                    if (res.code === 0 && res.data) {
                        // 登录成功
                        uni.setStorageSync("token", res.data.accessToken);
                        uni.setStorageSync("refreshToken", res.data.refreshToken); 
                        uni.setStorageSync("userId", res.data.userId);
                        uni.setStorageSync("expiresTime", res.data.expiresTime);
                        // 跳转到首页
                        uni.reLaunch({
                            url: "/pages/index/index",
                        });
                    } else {
                        // 登录失败，处理不同的错误码
                        let errorMsg = res.msg || "验证码登录失败";
                        
                        // 可以根据具体的错误码给出更友好的提示
                        // 例如：验证码错误、验证码过期等
                        if (res.code === 1002000008) {
                            errorMsg = "验证码错误，请重新输入";
                        } else if (res.code === 1002000009) {
                            errorMsg = "验证码已过期，请重新获取";
                        }
                        
                        uni.showToast({
                            title: errorMsg,
                            icon: "none",
                        });
                        
                        // 如果是验证码错误，清空验证码输入框
                        if (res.code === 1002000008) {
                            this.smsCode = [];
                            this.codeIndex = 0;
                        }
                    }
                })
                .catch((err) => {
                    uni.hideLoading();
                    let errorMsg = "登录失败，请稍后再试";
                    
                    // 处理网络错误或其他异常
                    if (err.data && err.data.msg) {
                        errorMsg = err.data.msg;
                    } else if (err.msg) {
                        errorMsg = err.msg;
                    }
                    
                    uni.showToast({
                        title: errorMsg,
                        icon: "none",
                    });
                    console.error("短信登录失败:", err);
                });
        },
        handleLogin() {
            if (!this.isAgree) {
                uni.showToast({
                    title: "请先同意用户协议",
                    icon: "none",
                });
                return;
            }

            if (!this.account) {
                uni.showToast({
                    title: "请输入账号",
                    icon: "none",
                });
                return;
            }

            if (!this.password) {
                uni.showToast({
                    title: "请输入密码",
                    icon: "none",
                });
                return;
            }

            // 调用账号密码登录接口
            uni.showLoading({
                title: "登录中...",
            });

            const data = {
                tenantName: "鼎和智耘管理平台",
                username: this.account,
                password: this.password,
            };

            user.login(data)
                .then((res) => {
                    uni.hideLoading();
                    
                    // 处理不同响应情况
                    if (res.code === 0 && res.data) {
                        // 登录成功
                        uni.setStorageSync("token", res.data.accessToken);
                        uni.setStorageSync("refreshToken", res.data.refreshToken);
                        uni.setStorageSync("userId", res.data.userId);
                        uni.setStorageSync("expiresTime", res.data.expiresTime);
                        // 跳转到首页
                        uni.reLaunch({
                            url: "/pages/index/index",
                        });
                    } else {
                        // 登录失败
                        uni.showToast({
                            title: res.msg || "登录失败",
                            icon: "none",
                        });
                    }
                })
                .catch((err) => {
                    uni.hideLoading();
                    uni.showToast({
                        title: err.msg || "登录失败，请稍后再试",
                        icon: "none",
                    });
                    console.error("账号密码登录失败:", err);
                });
        },
        toForgotPassword() {
            uni.navigateTo({
                url: "/pages/login/forgotPassword",
            });
        },
    },
    beforeDestroy() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    },
};
</script>

<style lang="scss">
.login-container {
    min-height: 100vh;
    padding: 150rpx 60rpx 0;
    background-color: #fff;
    display: flex;
    flex-direction: column;

    .header {
        position: absolute;
        left: 20rpx;
        top: 80rpx;
        height: 88rpx;
        display: flex;
        align-items: center;
        margin-top: 20rpx;

        .back-icon {
            padding: 10rpx;
        }
    }

    .logo-box {
        margin-top: 40rpx;
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        .logo {
            width: 262rpx;
            height: 90rpx;
        }

        .app-name {
            margin-top: 30rpx;
            font-size: 48rpx;
            font-weight: bold;
            color: #333;
        }

        .app-desc {
            margin-top: 10rpx;
            font-size: 28rpx;
            color: #666;
        }
    }

    .page-title {
        font-size: 40rpx;
        font-weight: 600;
        color: #333;
        margin-top: 30rpx;
    }

    .page-subtitle {
        font-size: 28rpx;
        color: #999;
        margin-top: 10rpx;
        margin-bottom: 30rpx;
    }

    .form-box {
        margin-top: 60rpx;

        .input-item {
            display: flex;
            align-items: center;
            height: 100rpx;
            border-bottom: 1px solid #eeeeee;
            margin-bottom: 30rpx;

            input {
                flex: 1;
                height: 100%;
                font-size: 30rpx;
            }

            .placeholder {
                color: #999;
            }

            .eye-icon {
                padding: 0 10rpx;
            }
        }

        .verify-code-input {
            display: flex;
            justify-content: flex-start;
            margin-bottom: 60rpx;

            .code-item {
                margin-right: 20rpx;
                width: 64rpx;
                height: 64rpx;
                border: 1px solid #eeeeee;
                border-radius: 8rpx;
                display: flex;
                justify-content: center;
                align-items: center;

                input {
                    width: 100%;
                    height: 100%;
                    text-align: center;
                    font-size: 36rpx;
                    color: #333;
                }
            }
        }

        .resend-btn {
            text-align: left;
            font-size: 28rpx;
            color: #2eb57d;
            margin-top: 60rpx;
        }

        .forgot-password {
            text-align: left;
            font-size: 26rpx;
            color: #000;
            margin-bottom: 60rpx;
        }

        .login-btn {
            height: 90rpx;
            line-height: 90rpx;
            text-align: center;
            background-color: #2eb57d;
            color: #fff;
            font-size: 32rpx;
            border-radius: 12rpx;
            margin-bottom: 40rpx;
        }

        .bottom-options {
            margin-top: 40rpx;
        }

        .switch-login {
            text-align: left;
            font-size: 28rpx;
            color: rgba(0, 0, 0, 1);
            margin-bottom: 60rpx;
        }

        .agreement {
            text-align: left;
            font-size: 24rpx;
            color: #999;

            checkbox {
                transform: scale(0.7);
                margin-right: 8rpx;
            }

            label {
                display: flex;
                justify-content: flex-start;
                align-items: center;
            }

            .link {
                color: #2eb57d;
            }
        }
    }
}
</style>
